package com.dis.service.service.impl;

import com.dis.pojo.dto.MenuTreeDTO;
import com.dis.pojo.entity.Permission;
import com.dis.service.service.PermissionService;
import com.dis.service.mapper.PermissionMapper;
import com.dis.service.mapper.RolePermissionMapper;
import com.dis.service.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Permission> getAllPermissions() {
        return permissionMapper.selectAll();
    }

    @Override
    public List<MenuTreeDTO> getPermissionTree() {
        // 获取所有权限
        List<Permission> permissions = permissionMapper.selectAll();
        // 转换为树形结构
        return buildPermissionTree(permissions);
    }

    @Override
    public List<Long> getPermissionIdsByRoleId(Long roleId) {
        return rolePermissionMapper.selectPermissionIdsByRoleId(roleId);
    }
    
    @Override
    public List<Permission> getPermissionsByRoleId(Long roleId) {
        List<Long> permissionIds = rolePermissionMapper.selectPermissionIdsByRoleId(roleId);
        if (permissionIds.isEmpty()) {
            return new ArrayList<>();
        }
        return permissionMapper.selectByIds(permissionIds);
    }

    @Override
    public List<MenuTreeDTO> getMenuTreeByUserId(Long userId) {
        try {
            // 添加调试日志
            System.out.println("获取菜单树，用户ID: " + userId);
            
            // 判断是否为超级管理员
            boolean isAdmin = permissionMapper.isUserAdmin(userId);
            System.out.println("是否为超级管理员: " + isAdmin);
            
            List<Permission> menus = new ArrayList<>();
            if (isAdmin) {
                // 超级管理员获取所有菜单
                menus = permissionMapper.selectAll().stream()
                        .filter(p -> p.getPermissionType() == 1) // 只过滤菜单类型
                        .collect(Collectors.toList());
                System.out.println("超级管理员菜单数量: " + menus.size());
            } else {
                try {
                    // 从数据库获取用户的角色编码
                    Integer roleCode = getUserRoleCode(userId);
                    System.out.println("用户角色编码: " + roleCode);
                    
                    if (roleCode != null) {
                        // 根据角色编码查询菜单
                        menus = permissionMapper.selectMenusByRoleCode(roleCode.toString());
                        System.out.println("根据角色编码查询菜单数量: " + (menus != null ? menus.size() : "null"));
                        
                        // 如果通过角色编码没有查询到菜单，尝试通过角色ID查询
                        if (menus == null || menus.isEmpty()) {
                            // 假设角色ID与角色编码相同，这里需要根据实际情况调整
                            Long roleId = roleCode.longValue() + 1; // 假设角色ID比角色编码大1
                            System.out.println("尝试通过角色ID查询菜单，角色ID: " + roleId);
                            menus = permissionMapper.selectMenusByRoleId(roleId);
                            System.out.println("通过角色ID查询菜单数量: " + (menus != null ? menus.size() : "null"));
                        }
                    }
                    
                    // 如果仍然没有查询到菜单，尝试直接通过用户ID查询
                    if (menus == null || menus.isEmpty()) {
                        menus = permissionMapper.selectMenusByUserId(userId);
                        System.out.println("通过用户ID查询菜单数量: " + (menus != null ? menus.size() : "null"));
                    }
                } catch (Exception e) {
                    System.err.println("查询用户菜单出错: " + e.getMessage());
                    e.printStackTrace();
                    // 发生错误时返回空列表
                    menus = new ArrayList<>();
                }
            }
            
            // 转换为树形结构
            List<MenuTreeDTO> menuTree = buildPermissionTree(menus);
            System.out.println("菜单树节点数量: " + (menuTree != null ? menuTree.size() : "null"));
            
            return menuTree;
        } catch (Exception e) {
            System.err.println("获取菜单树出错: " + e.getMessage());
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public List<String> getPermissionCodesByUserId(Long userId) {
            // 判断是否为超级管理员
        boolean isAdmin = permissionMapper.isUserAdmin(userId);
    
        if (isAdmin) {
            // 超级管理员返回通配符权限
            List<String> adminPermissions = new ArrayList<>();
            adminPermissions.add("*:*:*");
            return adminPermissions;
        }
        // 获取用户所有权限
        List<Permission> permissions = permissionMapper.selectApisByUserId(userId);
        // 提取权限编码
        return permissions.stream()
                .map(Permission::getPermissionCode)
                .collect(Collectors.toList());
    }

    @Override
    public boolean addPermission(Permission permission) {
        return permissionMapper.insert(permission) > 0;
    }

    @Override
    public boolean updatePermission(Permission permission) {
        return permissionMapper.update(permission) > 0;
    }

    @Override
    public boolean deletePermission(Long id) {
        return permissionMapper.deleteById(id) > 0;
    }

    @Override
    public Permission getById(Long id) {
        return permissionMapper.selectById(id);
    }

    /**
     * 构建权限树
     */
    private List<MenuTreeDTO> buildPermissionTree(List<Permission> permissions) {
        List<MenuTreeDTO> tree = new ArrayList<>();
        
        // 转换为MenuTreeDTO
        List<MenuTreeDTO> nodes = permissions.stream().map(p -> {
            MenuTreeDTO node = new MenuTreeDTO();
            node.setId(p.getId());
            node.setLabel(p.getPermissionName());
            node.setPermissionName(p.getPermissionName());
            node.setPermissionCode(p.getPermissionCode());
            node.setPermissionType(p.getPermissionType());
            node.setParentId(p.getParentId());
            node.setPath(p.getPath());
            node.setComponent(p.getComponent());
            node.setIcon(p.getIcon());
            node.setSort(p.getSort());
            node.setStatus(p.getStatus());
            node.setChildren(new ArrayList<>());
            return node;
        }).collect(Collectors.toList());
        
        // 构建树形结构
        for (MenuTreeDTO node : nodes) {
            if (node.getParentId() == 0) {
                tree.add(node);
            } else {
                for (MenuTreeDTO parent : nodes) {
                    if (parent.getId().equals(node.getParentId())) {
                        parent.getChildren().add(node);
                        break;
                    }
                }
            }
        }
        
        return tree;
    }

    /**
     * 获取用户的角色编码
     */
    private Integer getUserRoleCode(Long userId) {
        try {
            // 直接从数据库查询用户角色编码
            System.out.println("查询用户角色编码，用户ID: " + userId);
            
            // 从用户表中查询角色编码
            Integer roleCode = userMapper.getById(userId).getRoleCode();
            
            // 检查角色权限关联情况
            if (roleCode != null) {
                // 直接通过角色编码查询角色ID
                Long roleId = Long.valueOf(roleCode + 1); // 角色ID = 角色编码 + 1
                List<Long> permissionIds = rolePermissionMapper.selectPermissionIdsByRoleId(roleId);
                System.out.println("角色ID=" + roleId + "的权限ID列表: " + 
                                  (permissionIds != null ? permissionIds : "null") + 
                                  ", 数量: " + (permissionIds != null ? permissionIds.size() : 0));
            }
            
            // 检查所有权限
            List<Permission> allPermissions = permissionMapper.selectAll();
            System.out.println("系统所有权限数量: " + (allPermissions != null ? allPermissions.size() : 0));
            
            // 检查菜单类型权限
            List<Permission> menuPermissions = allPermissions.stream()
                .filter(p -> p.getPermissionType() == 1)
                .collect(Collectors.toList());
            System.out.println("系统菜单类型权限数量: " + menuPermissions.size());
            
            return roleCode;
        } catch (Exception e) {
            System.err.println("获取用户角色编码出错: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}
